package org.coody.gitee.fuzzer;

import java.text.MessageFormat;

import org.coody.gitee.entity.GiteeEntity;
import org.coody.gitee.exception.FuzzerException;
import org.coody.gitee.exception.LoginException;
import org.coody.gitee.fuzzer.iface.GiteeFuzzer;
import org.coody.gitee.util.HttpUtil;
import org.coody.gitee.util.HttpUtil.HttpEntity;
import org.coody.gitee.util.StringUtil;

public class GiteeLoginFuzzer extends GiteeFuzzer{

	
	public static String createAccount() {
		Integer num=StringUtil.getRanDom(5, 10);
		String chars = "abcdefghijklmnopqrstuvwxyz";
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<num;i++) {
			sb.append(chars.charAt((int)(Math.random() * 26)));
		}
		return sb.toString();
	}

	@Override
	public void fuzzer(GiteeEntity giteeEntity) throws FuzzerException {
		String postData = MessageFormat.format(
				"utf8=%E2%9C%93&authenticity_token={0}&redirect_to_url=&user%5Blogin%5D={1}&user%5Bpassword%5D={2}&captcha=&user%5Bremember_me%5D=0&user%5Bremember_me%5D=1&commit=%E7%99%BB+%E5%BD%95",
				giteeEntity.getCsrfToken(), giteeEntity.getEmail(), giteeEntity.getPassword());
		HttpEntity entity = HttpUtil.Post("https://gitee.com/login", postData, "utf-8", giteeEntity.getCookie(), giteeEntity.buildHeader());
		if(entity.getCode()!=302) {
			throw new LoginException("登录失败>>"+giteeEntity.getEmail());
		}
		String targeUrl=entity.getHeadMap().get("Location");
		String spaceUrl="https://gitee.com/" + giteeEntity.getSpace() + "/events";
		if(!spaceUrl.equals(targeUrl)) {
			throw new LoginException("登录失败>>"+giteeEntity.getEmail()+"::"+targeUrl);
		}
		giteeEntity.setCookie(entity.getCookie());
		// 访问个人中心
		entity = HttpUtil.Get(spaceUrl, "utf-8", giteeEntity.getCookie());
		giteeEntity.setCookie(entity.getCookie());
		// 刷新csrfToken
		String csrfToken=getCsrfToken(entity.getHtml());
		giteeEntity.setCsrfToken(csrfToken);
	}
}
